package com.ywk.base.javaBase.collection.map.myCache;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 通过HashMap实现本地缓存
 *
 * @Author zbh
 * @Date 2023/4/10
 */
@RestController
@RequestMapping("cacheByMapControl")
public class CacheByMapControl {

    private static Map<String, Object> finalQYMap = new HashMap<>();
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @RequestMapping(value = "/getToken")
    public String test() {
        if (finalQYMap.size() > 0 && finalQYMap.get("test") != null) {
            CacheInit init = (CacheInit) finalQYMap.get("test");
            Calendar applyTime = Calendar.getInstance();
            applyTime.setTime(init.getApplyTime());
            Calendar nowTime = Calendar.getInstance();
            nowTime.setTime(new Date());
            //缓存 10s 内有效
            if (nowTime.compareTo(applyTime) < 0) {
                System.out.println("缓存获取时间：" + dateFormat.format(new Date()));
                return init.getAccessToken();
            }

        }
        String token = "testToken123456";
        CacheInit init = new CacheInit();
        init.setAccessToken(token);
        Date now = new Date();
        Calendar applyTime = Calendar.getInstance();
        applyTime.setTime(now);
        //设置缓存有效时 10秒
        applyTime.add(Calendar.SECOND, 10);
        init.setApplyTime(applyTime.getTime());
        System.out.println("非缓存获取token时间：" + dateFormat.format(new Date()));
        finalQYMap.put("test", init);

        return token;
    }
}